package com.gmail.bogatyr.alexander.server.dao;

import com.google.inject.Inject;
import com.gmail.bogatyr.alexander.shared.entity.TelephoneBook;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import javax.persistence.EntityManager;
import java.util.List;

import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.hibernate.criterion.MatchMode.ANYWHERE;

public class TelephoneBookDao extends BaseDao<TelephoneBook> implements ITelephoneBookDao {

    @Inject
    public TelephoneBookDao(EntityManager em) {
        super(TelephoneBook.class, em);
    }

    @Override
    public List<TelephoneBook> find(String number, String name) {
        if (isEmpty(number) && isEmpty(name)) return null;

        Criteria criteria = getSession().createCriteria(TelephoneBook.class);
        if (isNotEmpty(number)) criteria.add(Restrictions.eq("number", number));
        if (isNotEmpty(name)) criteria.add(Restrictions.like("name", name, ANYWHERE));
        
        return criteria.list();
    }
}
